using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TTSoft.MyWeb.Controllers
{
	#region using
	using System;
	using System.Web.Mvc;
	using System.Web.Security;
	using System.Collections.Generic;
	using TTSoft.MyWeb.Models.ViewModels;
	using TTSoft.MyWeb.Models.Repositories;
	using TTSoft.MyWeb.Helpers;
	using TTSoft.MyWeb.Models;
	using System.IO;
	#endregion
	public abstract class BaseController : Controller
	{
		protected ThuocRepository _repThuoc = new ThuocRepository();
		protected LoaiThuocRepository _repLoaiThuoc = new LoaiThuocRepository();
		protected NguoiDungRepository _repNguoiDung = new NguoiDungRepository();

		protected string RenderPartialViewToString()
		{
			return RenderPartialViewToString(null, null);
		}

		protected string RenderPartialViewToString(string viewName)
		{
			return RenderPartialViewToString(viewName, null);
		}

		protected string RenderPartialViewToString(string viewName, object model)
		{
			if (string.IsNullOrEmpty(viewName))
				viewName = ControllerContext.RouteData.GetRequiredString("action");
			ViewData.Model = model;
			using (StringWriter sw = new StringWriter())
			{
				ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
				ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
				viewResult.View.Render(viewContext, sw);
				return sw.GetStringBuilder().ToString();
			}
		}


		public GroupViewModel CreateViewModel(DataTransferViewModel dataTransfer)
		{
			GroupViewModel viewModel = new GroupViewModel();
			if (dataTransfer.EnumViewModelType.ToString().Contains("ADMIN"))
			{
                viewModel.LoaiThuocModel = RetrieveLoaiThuocViewModel(dataTransfer);
			}
			switch (dataTransfer.EnumViewModelType)
			{
				case EnumViewModel.ADMIN_DETAILOF_THUOC:
                    viewModel.ThuocModel = RetrieveDetailOfThuocViewModel(dataTransfer);
					break;
                case EnumViewModel.ADMIN_DETAILOF_NGUOIDUNG:
                    viewModel.NguoiDungModel = RetrieveDetailOfNguoiDungViewModel(dataTransfer);
                    break;
				case EnumViewModel.ADMIN_THUOC:
                    viewModel.ThuocModel = RetrieveThuocViewModel(dataTransfer);
					break;
				case EnumViewModel.ADMIN_LOAITHUOC:
					break;
				case EnumViewModel.ADMIN_NGUOIDUNG:
                    viewModel.NguoiDungModel = RetrieveNguoiDungViewModel(dataTransfer);
					break;
				case EnumViewModel.HOME_REGISTER:
					break;
				case EnumViewModel.HOME_DETAILOF_NGUOIDUNG:
					break;
                case EnumViewModel.ADMIN_ENTER_SEARCH_THUOC:
                    break;
                case EnumViewModel.ADMIN_SEARCH_THUOC:
                    viewModel.ThuocModel = RetrieveResultSearchThuocViewModel(dataTransfer);
                    break;
			}
			return viewModel;
		}

		public bool UploadFile(HttpPostedFileBase file, string path, string name, ref string refName)
		{
			try
			{
				if (!System.IO.File.Exists(Server.MapPath(path + file.FileName)))
				{
					FileInfo f = new FileInfo(file.FileName);
					long ngay = DateTime.Now.ToBinary();
					refName = name + ngay + f.Extension;
					string fullPath = path + refName;
					if (file == null)
					return false;
					byte[] buffer = new byte[file.ContentLength];
					file.InputStream.Read(buffer, 0, file.ContentLength);
					FileStream newFile = new FileStream(Server.MapPath(fullPath), FileMode.Create, FileAccess.Write);
					newFile.Write(buffer, 0, file.ContentLength);
					newFile.Close();
				}
				else
				{
					refName = file.FileName;
				}
				return true;
			}
			catch
			{
				return false;
			}
		}

		public void DeleteFile(string filePath)
		{
			FileInfo file = new FileInfo(filePath);
			if (file.Exists)
			{
				file.Delete();
			}
		}

		public bool SendingMail(string subject, string emailContent, string to)
		{
			bool result = false;
			try
			{
				System.Net.Mail.SmtpClient mailclient = new System.Net.Mail.SmtpClient();
				System.Net.NetworkCredential auth = new System.Net.NetworkCredential(WebConfiguration.EmailLienHe, WebConfiguration.PasswordEmailLienHe);
				mailclient.Host = WebConfiguration.MailServer;
				mailclient.EnableSsl = true;
				mailclient.UseDefaultCredentials = true;
				mailclient.Credentials = auth;
				System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(WebConfiguration.EmailLienHe, to);
				mm.Subject = subject;
				mm.IsBodyHtml = true;
				mm.Body = emailContent;
				mailclient.Send(mm);
				result = true;
			}
			catch
			{
				result = false;
			}
			return result;
		}

        public ThuocViewModel RetrieveResultSearchThuocViewModel(DataTransferViewModel dataTransfer)
        {
            var lst = _repThuoc.SearchThuoc(dataTransfer.Search_TenThuoc, dataTransfer.Search_NuocSanXuat);
            var totalitem = lst.Count;
            return new ThuocViewModel
            {
                GetModel = new GetThuocViewModel
                {
                    LstObjModel = lst,
                    TotalItem = totalitem,
                    CurrentPage = dataTransfer.CurrentPage
                },
                AddModel = new AddThuocViewModel
                {
                },
                EditModel = new EditThuocViewModel
                {
                    ID = dataTransfer.IntID,
                },
                ReferKeys = new ThuocReferKeys()
                {
                    IDLoaiThuoc = dataTransfer.IDLoaiThuoc,
                },
                InfoText = dataTransfer.InfoText
            };
        }

		public ThuocViewModel RetrieveThuocViewModel(DataTransferViewModel dataTransfer)
		{
			List<Thuoc> lst = null;
			int totalitem = -1;
			if (dataTransfer.IDLoaiThuoc != -1)
			{
				lst = _repThuoc.SelectByIDLoaiThuoc(dataTransfer.IDLoaiThuoc, dataTransfer.CurrentPage, WebConfiguration.NumThuocPerPage);
				totalitem = _repThuoc.GetTotalItemByIDLoaiThuoc(dataTransfer.IDLoaiThuoc);
			}
			else
			{
				lst = _repThuoc.SelectPaging(dataTransfer.CurrentPage, WebConfiguration.NumThuocPerPage);
				totalitem = _repThuoc.GetTotalItem();
			}
			return new ThuocViewModel
			{
				GetModel = new GetThuocViewModel
				{
					LstObjModel = lst,
					TotalItem = totalitem,
					CurrentPage = dataTransfer.CurrentPage
				},
				AddModel = new AddThuocViewModel
				{
				},
				EditModel = new EditThuocViewModel
				{
					ID = dataTransfer.IntID,
				},
				ReferKeys = new ThuocReferKeys()
				{
					IDLoaiThuoc = dataTransfer.IDLoaiThuoc,
				},
				InfoText = dataTransfer.InfoText
			};
		}

		public LoaiThuocViewModel RetrieveLoaiThuocViewModel(DataTransferViewModel dataTransfer)
		{
			return new LoaiThuocViewModel
			{
				GetModel = new GetLoaiThuocViewModel
				{
					LstObjModel = _repLoaiThuoc.SelectAll(),
					TotalItem = _repLoaiThuoc.GetTotalItem(),
					CurrentPage = dataTransfer.CurrentPage
				},
				AddModel = new AddLoaiThuocViewModel
				{
				},
				EditModel = new EditLoaiThuocViewModel
				{
					ID = dataTransfer.IntID,
				},
				InfoText = dataTransfer.InfoText
			};
		}


		public NguoiDungViewModel RetrieveNguoiDungViewModel(DataTransferViewModel dataTransfer)
		{
			return new NguoiDungViewModel
			{
				GetModel = new GetNguoiDungViewModel
				{
					LstObjModel = _repNguoiDung.SelectPaging(dataTransfer.CurrentPage, WebConfiguration.NumNguoiDungPerPage, dataTransfer.Role),
					TotalItem = _repNguoiDung.GetTotalItem(dataTransfer.Role),
					CurrentPage = dataTransfer.CurrentPage
				},
				AddModel = new AddNguoiDungViewModel
				{
				},
				EditModel = new EditNguoiDungViewModel
				{
					ID = dataTransfer.GuidID,
				}
			};
		}

		public ThuocViewModel RetrieveDetailOfThuocViewModel(DataTransferViewModel dataTransfer)
		{
			return new ThuocViewModel
			{
				GetModel = new GetThuocViewModel
				{
					LstObjModel = _repThuoc.RetrieveByID(dataTransfer.IntID)
				},
				EditModel = new EditThuocViewModel
				{
					ID = dataTransfer.IntID,
				},
				InfoText = dataTransfer.InfoText
			};
		}

        public NguoiDungViewModel RetrieveDetailOfNguoiDungViewModel(DataTransferViewModel dataTransfer)
        {
            return new NguoiDungViewModel
            {
                GetModel = new GetNguoiDungViewModel
                {
                    LstObjModel = _repNguoiDung.RetrieveByID(dataTransfer.GuidID)
                },
                EditModel = new EditNguoiDungViewModel
                {
                    ID = dataTransfer.GuidID,
                },
                InfoText = dataTransfer.InfoText
            };
        }
	}
}